package com.dpj.book.service.impl;

import com.dpj.book.mapper.CartItemMapper;
import com.dpj.book.mapper.OrderItemMapper;
import com.dpj.book.mapper.OrderMapper;
import com.dpj.book.pojo.CartItem;
import com.dpj.book.pojo.OrderBean;
import com.dpj.book.pojo.OrderItem;
import com.dpj.book.pojo.User;
import com.dpj.book.service.OrderService;
import com.dpj.book.utils.SqlSessionFactoryUtils1;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;
import java.util.Map;

public class OrderServiceImpl implements OrderService {
    SqlSessionFactory sessionFactory = SqlSessionFactoryUtils1.getSessionFactory();
    @Override
    public void addOrderBean(OrderBean orderBean) {
        //1订单表添加一条记录
        //2订单详情表添加7条记录
        //3购物车项表中删除对顶的7条记录
        SqlSession sqlSession = sessionFactory.openSession(true);
        OrderMapper ordermapper = sqlSession.getMapper(OrderMapper.class);
        //第一步
        ordermapper.addOrderBean(orderBean);//主键返回，所以orderBean的id是有值的
        //第二步

        OrderItemMapper orderItemMapper = sqlSession.getMapper(OrderItemMapper.class);
        CartItemMapper cartItemMapper = sqlSession.getMapper(CartItemMapper.class);
        User orderUser = orderBean.getOrderUser();
        //orderBean中的orderItemList是空的，此处我么应该根据用户的购物车中的购物车中项去一个个转换成底单项
        Map<Integer, CartItem> cartItemMap = orderUser.getCart().getCartItemMap();
        for (CartItem cartItem : cartItemMap.values()) {
            OrderItem orderItem=new OrderItem();
            orderItem.setBook(cartItem.getBook());
            orderItem.setBuyCount(cartItem.getBuyCount());
            orderItem.setOrderBean(orderBean);
            orderItemMapper.addOrderItem(orderItem);
        }
        //第三步
        for (CartItem cartItem : cartItemMap.values()) {
            cartItemMapper.deleteCartIem(cartItem);
        }



    }

    @Override
    public List<OrderBean> getAllOrder(User user) {
        SqlSession sqlSession = sessionFactory.openSession(true);
        OrderMapper ordermapper = sqlSession.getMapper(OrderMapper.class);
        OrderItemMapper orderItemMapper = sqlSession.getMapper(OrderItemMapper.class);
        List<OrderBean> orderBeanList= ordermapper.getAllOrder(user);
        //为每一条订单查询对应的订单条数并设置进去
        for (OrderBean orderBean : orderBeanList) {
            Integer id = orderBean.getId();
            int count=orderItemMapper.getCount(id);
            orderBean.setOrderCount(count);
        }
        return orderBeanList;
    }
}
